
<?php
// 配置文件路径
$config = [
    'playTimesPath' => __DIR__ . "/play_times_fh.txt",
    'adUrlPath' => __DIR__ . "/ad_url_fh.txt",
    'lastTimeCachePath' => __DIR__ . "/last_time_fh.json",
    'cvsPath' => __DIR__ . "/cvs_fh.txt",
    'tokenPath' => __DIR__ . "/token_fh.txt",
    'filePath' => __DIR__ . "/list_fh.json",
    'proxyPath' => __DIR__ . "/list_fh.txt",
    'cacheFile' => __DIR__ . '/cache/fh6_redirect_urls.json',
    
    // API配置
    'loginUrl' => "http://60.fhtvs.top:2013/api/luotuo/login",
    'renewApi' => "http://60.fhtvs.top:2013/api/luotuo/act3",
    'passwordApiUrl' => "https://tdcq.scwlnet.cn/fenghuang.php",
    'passwordApiUrl2' => "https://tdcq.scwlnet.cn/kdsm.php",
    
    // 应用配置
    'app_name' => "凤凰TV6.6",
    'package_name' => "feng.shiwh.sjhdu",
    'sign' => "AD80F93B542B",
    'fixedStr' => "12315",
    
    // 代理IP池
    'proxyPool' => [
        'http://proxy1.example.com:8080',
        'http://proxy2.example.com:8080',
        'http://proxy3.example.com:8080'
    ],
    
    // 请求限制
    'rateLimit' => 5, // 每秒请求数限制
    'userAgents' => [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)'
    ]
];

// 初始化随机代理和用户代理
function initRequestConfig($config) {
    $proxy = $config['proxyPool'][array_rand($config['proxyPool'])];
    $userAgent = $config['userAgents'][array_rand($config['userAgents'])];
    
    return [
        'proxy' => $proxy,
        'userAgent' => $userAgent,
        'timeout' => 10
    ];
}

// 带频率控制的请求函数
function safeRequest($url, $config) {
    static $lastRequestTime = 0;
    
    // 频率控制
    $elapsed = microtime(true) - $lastRequestTime;
    if ($elapsed < (1 / $config['rateLimit'])) {
        usleep((1 / $config['rateLimit'] - $elapsed) * 1000000);
    }
    
    $requestConfig = initRequestConfig($config);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_PROXY, $requestConfig['proxy']);
    curl_setopt($ch, CURLOPT_USERAGENT, $requestConfig['userAgent']);
    curl_setopt($ch, CURLOPT_TIMEOUT, $requestConfig['timeout']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $lastRequestTime = microtime(true);
    
    if (curl_errno($ch)) {
        error_log("请求失败: " . curl_error($ch));
        return false;
    }
    
    curl_close($ch);
    return $response;
}

$proxyUrl = "https://gitee.com/yu-xinhao008/love-shadow-guest/edit/master/qw.php";  //这里改成你的php路径


const GARTHER_TYPE = 1;  //0 => 每个频道只采集首条线路，1 =>  每个频道采集所有线路
const TOKEN_NAME = "TokenModel"; //凤凰播放链接的token参数名 http://60.fhtvs.top:2060/play/forward/4?tvid=143&TokenModel=4ffb4a481e82650b34fe3006eb048889&chid=1254


const MAC = "00:cc:42:3e:28:78"; //设备号，自己改成其他的，避免挤号（备）
const ANDROID_ID = "fc1736bcde84e439"; //随便改几个数字 字母（备）




const RAND = ""; //凤凰不需要rand 参数,不用修改
const TOKEN_TIMEOUT = 60 * 3; //token缓存超时，建议不超过3分钟
const CACHE_TIME = 60 * 40; // flv推流地址，本地缓存时间
const ISAUTH = true; //验证码开关
const AUTH_TYPE = 0;  // 0=> 固定验证码   1=>时间戳验证，可设置url超时后失效
const AUTH_TIMEOUT = 60 * 60 * 5;  //(启用时间戳验证时生效) 超时5小时，链接失效，可通过http://你的域名/qwt.php?update 试试获取拿到最新链接
const AUTH_TIMEOUT_KEY = "12345abcde666666";  //(启用时间戳验证时生效) AES 秘钥
const AUTH_URL = "https://txmov2.a.kwimgs.com/upic/2025/07/05/11/BMjAyNTA3MDUxMTM4NDZfMjU5MjExMDg3MF8xNjg1NjM2MDU4ODNfMF8z_b_B03640a9718e7526b7404b87b8f2";//验证码错误，或N次播放，跳广告的链接
const AUTH_KEY = "666"; //当前验证码（验证码开关为开，且启用 固定验证码 时，才有效）
const FAIL_URL = "https://txmov2.a.kwimgs.com/upic/2025/04/16/13/BMjAyNTA0MTYxMzE3MjNfMjU5MjExMDg3MF8xNjE4NzA0MzI0NDFfMF8z_b_B177bc8c9b41a4cc994f5fefebac59.mp4";//当全网通出现赞赏码广告时，播放此默认视频
const RAND_AD = false; // 每n次播放，跳转广告 开关  false = 关   true = 开
const RAND_AD_TIMESOUT = 10;  //每n次播放，跳转广告


/**
 * 获取最新列表
 * https://gitee.com/yu-xinhao008/love-shadow-guest/edit/master/qw.php?update
 *
 */


//echo  login($loginUrl);
//echo updateStatus($cvsPath, $filePath, $proxyPath, $tokenPath);
//echo renew();


if (isset($_GET['update'])) {

    header('Content-Type: text/plain');
    echo updateStatus($cvsPath, $filePath, $proxyPath, $tokenPath);

} else if (isset($_GET['id']) && isset($_GET['t'])) {
    $t = $_GET['t'];
    $id = $_GET['id'];
    $l = $_GET['l'] ?? 0;

    if (RAND_AD) {
        if (file_exists($playTimesPath)) {
            $times = file_get_contents($playTimesPath);
            if ($times > RAND_AD_TIMESOUT) {
                file_put_contents($playTimesPath, 0);
                header('Location:' . AUTH_URL);
                //echo AUTH_URL;
                exit();
            } else {
                $times++;
                file_put_contents($playTimesPath, $times);
            }
        } else {
            file_put_contents($playTimesPath, 0);
        }
    }

    if (ISAUTH) {
        if (isset($_GET['auth']) && !empty($_GET['auth'])) {
            if (AUTH_TYPE == 0 && $_GET['auth'] !== AUTH_KEY) {
                header('Location:' . AUTH_URL);
                //echo AUTH_URL;
                exit();
            } else if (AUTH_TYPE == 1) {
                $auth_decrypted = openssl_decrypt(hex2bin($_GET['auth']), "aes-128-ecb", AUTH_TIMEOUT_KEY, OPENSSL_RAW_DATA);
                if ($auth_decrypted === false || (time() - $auth_decrypted) > AUTH_TIMEOUT) {
                    header('Location:' . AUTH_URL);
                    //echo AUTH_URL;
                    exit();
                }
            }
        } else {
            header('Location:' . AUTH_URL);
            //echo AUTH_URL;
            exit();
        }
    }

    if (file_exists($adUrlPath) === false) {
        file_put_contents($adUrlPath, "");
    }

    $adUrl = file_get_contents($adUrlPath);
    $getCache = isCacheValid($t, $id, $l, $cacheFile);
    if ($getCache !== false) {
        if ($adUrl == $getCache) {
            $getCache = FAIL_URL;
        }
        header("Location:" . $getCache);
        //echo $getCache;
        exit();
    }


    $maxCount = 2;
    $count = 0;
    while ($count < $maxCount) {
        $url = "";
        $data = file_get_contents($filePath);
        $dataArray = json_decode($data, true);
        foreach ($dataArray as $group) {
            $gName = $group["name"];
            if ($gName == $t) {
                foreach ($group["data"] as $item) {
                    $cName = $item["name"];
                    if ($cName == $id) {
                        $url = $item["source"][$l] ?? "";
                    }
                }
            }
        }
        $nToken = file_get_contents($tokenPath);
        $url = preg_replace('/' . TOKEN_NAME . '=[0-9a-zA-Z]+/', TOKEN_NAME . "=" . $nToken, $url);
        if (strpos($url, "http") !== false) {
            $finalUrl = getRedirectedUrl($url);
        } else {
            $finalUrl = $url;
        }
        if (strpos($finalUrl, ".flv") !== false || strpos($finalUrl, ".m3u8") !== false) {
            if (isQRCodeUrl($id, $finalUrl, $lastTimeCachePath)) {
                //不同频道，url地址却一样，说明此链接是广告链接
                //可以进行一些操作，避免跳转到广告
                //file_put_contents($cacheFile, "");
                if ($adUrl !== $finalUrl) {
                    file_put_contents($adUrlPath, $finalUrl);
                }
                $finalUrl = FAIL_URL;
                if (isToeknValid($tokenPath) === false) {
                    updateStatus($cvsPath, $filePath, $proxyPath, $tokenPath);
                }
            } else {
                if ($adUrl != $finalUrl) {
                    setCache($t, $id, $l, $finalUrl, $cacheFile);
                }
            }
        }
        //如果重定向地址是mp4格式的，则判断为失效，再判断token缓存文件是否超过n分钟，则更新配置文件。避免重复高频次请求服务器，被封ip
        //遥控器广告url：https://video-zb.cloudvideocdn.taobao.com/73bbe9f95b148212/d4d9ee0db355d553/20241204_580825e6e04cc8cf_496863192271_207703408427494_published_mp4_264_hd_taobao.mp4?auth_key=1751181989-0-0-46b1fd8f7f4076b34d8c263e5a01b51b&biz=tbs_vsucai-b214d1377e723008&t=2150422e17511792891645742e18d5&t=2150422e17511792891645742e18d5&b=tbs_vsucai&p=cloudvideo_http_tb_seller_vsucai_publish
        if ((strpos($finalUrl, ".mp4") !== false || strpos($finalUrl, "forward") !== false) && isToeknValid($tokenPath) === false) {
            updateStatus($cvsPath, $filePath, $proxyPath, $tokenPath);
        }
        $count++;
    }

    $adUrl = file_get_contents($adUrlPath);
    if ($adUrl == $finalUrl || strpos($finalUrl, "forward") !== false) {
        $finalUrl = FAIL_URL;
    }

    header("Location: $finalUrl");
    //echo $finalUrl;
}


function login($url)
{
    global $app_name;
    $post_data = [
        "region" => "",
        "mac" => MAC,
        "androidid" => ANDROID_ID,
        "model" => "001-MNQ",
        "nettype" => "",
        "appname" => $app_name
    ];
    $md5_sign = generate_sign();
    $aes_key = substr($md5_sign, 5, 16);
    $encrypted_data = fetch_encrypted_data($url, $post_data, "login");

    if (!$encrypted_data) {
        echo FAIL_URL . "?获取登录数据失败";
        exit();
        die("无法获取加密数据");
    }

    $decrypted_data = aes_decrypt($encrypted_data, $aes_key);
    if (!$decrypted_data) {
        echo $encrypted_data;
        die("AES 解密失败");
    }
    return $decrypted_data;

}


function fetchData($url)
{
    global $app_name;
    $post_data = [
        "region" => "长沙",
        "mac" => MAC,
        "androidid" => ANDROID_ID,
        "model" => "001-MNQ",
        "nettype" => "长沙市 湖南 电信",
        "appname" => $app_name,
        "rand" => RAND
    ];

    $md5_sign = generate_sign();
    $aes_key = generate_aes_key($md5_sign, $post_data["rand"]);
    $encrypted_data = fetch_encrypted_data($url, $post_data, "data");

    if (!$encrypted_data) {
        die("无法获取加密数据");
    }

    $transformed_data = transform_encrypted_string($encrypted_data);
    $decrypted_data = aes_decrypt($transformed_data, $aes_key);
    if (!$decrypted_data) {
        die("AES 解密失败");
    }
    return str_replace("\u0026", "&", $decrypted_data);

}

function renew()
{
    global $renewApi, $passwordApiUrl;
    $data = curl_get($passwordApiUrl, []);
    $dataArr = json_decode($data, true);
    $secretKey = explode("：", $dataArr["rep_data_three"])[1];
    $post_data = [
        "mac" => MAC,
        "androidid" => ANDROID_ID,
        "model" => "001-MNQ",
        "sn" => $secretKey
    ];
    $encrypted_data = fetch_encrypted_data($renewApi, $post_data, "act");

//    if (strpos($encrypted_data, "成功") !== false) {
//        return $encrypted_data;
//    }
    return "本次注册码：" . $secretKey . "。充值结果：" . $encrypted_data;


}

function updateStatus($cvsPath, $filePath, $proxyPath, $tokenPath)
{
    global $proxyUrl, $loginUrl;
    $getver = curl_get("http://60.fhtvs.top:2013/api/luotuo/getver", ["accept:*/*", "Accept-Encoding:gzip", "connection:Keep-Alive", "user-agent:UA"]);
    $loginResult = login($loginUrl);

    $bg = curl_get("http://60.fhtvs.top:2013/api/luotuo/bg", ["accept:*/*", "Accept-Encoding:gzip", "connection:Keep-Alive", "user-agent:MyTV/1.0"]);
    $dataArray = json_decode($loginResult, true);
    $dataUrl = $dataArray["dataurl"];
    if (empty($dataUrl)) {
        $renewResult = renew();
        if (strpos($renewResult, "成功")) {
            $loginResult = login($loginUrl);
            $dataArray = json_decode($loginResult, true);
            $dataUrl = $dataArray["dataurl"];
        } else {
            echo "自动续费失败。";
            exit();
        }
    }

    $fetchResult = fetchData($dataUrl);
    $bgImg = curl_get($bg, ["Connection:Keep-Alive", "Accept-Encoding:gzip", "User-Agent:Dalvik/2.1.0 (Linux; U; Android 9; 001-MNQ Build/PQ3B.190801.06161913)"]);

    $fetchResult = str_replace(["CCTV5+", 'name":"香港"', 'name":"台湾"'], ["CCTV5P", 'name":"香港频道"', 'name":"台湾频道"'], $fetchResult);
    $channelArray = json_decode($fetchResult, true);
    $txt = "凤凰TV6.6,代理源\n\n";
    $cvs = "凤凰TV6.6,CVS格式化源\n\n";
    if (AUTH_TYPE == 1) {
        $authEncryptedSuffix = bin2hex(openssl_encrypt(time(), 'AES-128-ECB', AUTH_TIMEOUT_KEY, OPENSSL_RAW_DATA));
    }

    foreach ($channelArray as $group) {
        $gName = $group["name"];
        $gPwd = $group["psw"] ? "~" . $group["psw"] : "";
        if (strpos($gName, "密码") === false && strpos($gName, "我的收藏") === false) {
            $txt .= $gName . $gPwd . ",#genre#\n";
            $cvs .= $gName . $gPwd . ",#genre#\n";
            if (!empty($group["data"])) {
                $list = $group["data"];
                foreach ($list as $item) {
                    $cName = $item["name"];
                    $cUrlArr = $item["source"];
                    if (ISAUTH) {
                        if (AUTH_TYPE == 0) {
                            $authSuffix = "&auth=" . AUTH_KEY;
                        } elseif (AUTH_TYPE == 1) {
                            $authSuffix = "&auth=" . $authEncryptedSuffix;
                        }
                    } else {
                        $authSuffix = "";
                    }
                    if (GARTHER_TYPE == 1) {
                        for ($i = 0; $i < count($cUrlArr); $i++) {
                            if (strpos($cName, "密码") === false) {
                                $txt .= $cName . "," . $proxyUrl . "?t=$gName&l=$i&id=$cName" . $authSuffix . "\n";
                                $cvs .= $cName . "," . $cUrlArr[$i] . "\n";
                            }
                        }
                    } else {
                        $txt .= $cName . "," . $proxyUrl . "?t=$gName&id=$cName" . $authSuffix . "\n";
                        $cvs .= $cName . "," . $cUrlArr[0] . "\n";
                    }


                }
            }
        }
    }

    preg_match('/' . TOKEN_NAME . '=[0-9a-zA-Z]+/s', $fetchResult, $matches);
    $token = explode("=", $matches[0])[1];
    file_put_contents($tokenPath, $token);

    file_put_contents($cvsPath, $cvs);
    file_put_contents($filePath, $fetchResult);
    file_put_contents($proxyPath, $txt);
    return $txt;
}

function isToeknValid($tokenPath)
{
    if (file_exists($tokenPath)) {
        $fmtime = filemtime($tokenPath);
        $now = time();
        $diff = $now - $fmtime;
        if ($diff < TOKEN_TIMEOUT) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}

function isCacheValid($t, $id, $l, $cacheFile)
{
    $cacheTag = $t . "_" . $id . "_" . $l;
    $cacheDir = dirname($cacheFile);

    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }

    $cache = [];
    if (file_exists($cacheFile)) {
        $cacheData = file_get_contents($cacheFile);
        if ($cacheData !== false) {
            $cache = json_decode($cacheData, true) ?: [];
        }
    }

    $now = time();
    if (isset($cache[$cacheTag]) && isset($cache[$cacheTag]['url']) && isset($cache[$cacheTag]['time']) && ($now - $cache[$cacheTag]['time'] < CACHE_TIME)) {
        return $cache[$cacheTag]['url'];
    }
    return false;
}

function setCache($t, $id, $l, $finalUrl, $cacheFile)
{
    $cacheTag = $t . "_" . $id . "_" . $l;
    $cacheDir = dirname($cacheFile);

    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }

    if (file_exists($cacheFile)) {
        $cacheData = file_get_contents($cacheFile);
        if ($cacheData !== false) {
            $cacheData = json_decode($cacheData, true) ?? [];
        }
    } else {
        $cacheData = [];
    }

    $cacheData[$cacheTag] = [
        'url' => $finalUrl,
        'time' => time(),
    ];
    file_put_contents($cacheFile, json_encode($cacheData));

}


function getRedirectedUrl($url)
{
    $maxRedirects = 2; // 最大重定向次数，防止无限循环
    $redirectCount = 0;

    while ($redirectCount < $maxRedirects) {
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'User-Agent:Lavf/57.71.100'
        ));

        $response = curl_exec($ch);

        if ($response === false) {
            curl_close($ch);
            return null;
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $headerSize);

        curl_close($ch);

        if ($httpCode >= 300 && $httpCode < 400) {
            if (preg_match('/^Location:\s*(.*?)$/mi', $headers, $matches)) {
                $redirectUrl = trim($matches[1]);
                if (!filter_var($redirectUrl, FILTER_VALIDATE_URL)) {
                    $parsedUrl = parse_url($url);
                    if (isset($parsedUrl['scheme']) && isset($parsedUrl['host'])) {
                        $redirectUrl = rtrim($parsedUrl['scheme'] . '://' . $parsedUrl['host'], '/') . '/' . ltrim($redirectUrl, '/');
                    } else {
                        return $url;
                    }
                }

                // 检查重定向后的URL是否包含".php"
                if (stripos($redirectUrl, '.php') !== false) {
                    $url = $redirectUrl;
                    $redirectCount++;
                    continue; // 继续重定向
                } else {
                    return $redirectUrl; // 不包含".php"，返回当前重定向URL
                }
            } else {
                return $url;
            }
        } else {
            return $url;
        }
    }

    return $url; // 达到最大重定向次数，返回当前URL
}


function md5_hash($text)
{
    return md5($text);
}

function aes_decrypt($encrypted_data, $key)
{
    $encrypted_data = base64_decode($encrypted_data);
    return openssl_decrypt($encrypted_data, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
}


function fetch_encrypted_data($url, $post_data, $type)
{
    $params = $type . "=" . json_encode($post_data, JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_ENCODING, ''); // 自动处理所有支持的编码，包括gzip

    $default_headers = [
        'accept:*/*',
        'Accept-Encoding:gzip',
        'connection:Keep-Alive',
        'user-agent:MSIE',
        'Content-Type:application/x-www-form-urlencoded',
        'Content-Length:' . strlen($params)
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $default_headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    if ($response === false) {
        $error_message = curl_error($ch);
        echo "Curl error: " . $error_message;
        return false;
    }
    curl_close($ch);
    return $response;
}


function generate_aes_key($f4319D, $rand)
{
    $md5_hash = md5_hash($f4319D . $rand);
    return substr($md5_hash, 7, 16);
}

function zlib_decompress($data)
{
    return zlib_decode($data);
}

function transform_encrypted_string($data)
{
    $data = substr($data, 128);
    $data = str_replace(["f", "b", "t", "y"], ["#", "f", "%", "t"], $data);
    $data = str_replace(["#", "%"], ["b", "y"], $data);
    return $data;
}


function generate_sign()
{
    global $app_name, $package_name, $sign, $fixedStr;
    $first_hash = md5_hash($fixedStr . $app_name . $package_name . $sign);
    return md5_hash($first_hash . $app_name . $package_name);
}

function isQRCodeUrl($id, $finalUrl, $lastTimeCachePath)
{
    $initArr = [];
    $initArr[] = [
        "id" => $id,
        "url" => $finalUrl,
        "time" => time()
    ];
    $lastTimeContent = file_get_contents($lastTimeCachePath);
    if (!file_exists($lastTimeCachePath) || empty($lastTimeContent)) {
        setLastCache($initArr, $lastTimeCachePath);
        return false;
    }

    $ltcArr = json_decode($lastTimeContent, true);
    if ($ltcArr[0]['id'] != $id && $ltcArr[0]['url'] == $finalUrl) {
        setLastCache($initArr, $lastTimeCachePath);
        return true;
    }

    setLastCache($initArr, $lastTimeCachePath);
    return false;

}

function setLastCache($initArr, $lastTimeCachePath)
{
    file_put_contents($lastTimeCachePath, json_encode($initArr));
}

function generateRandom16BitId()
{
    $characters = '0123456789abcdef';
    $randomId = '';
    for ($i = 0; $i < 16; $i++) {
        $randomId .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomId;
}

function generateRandomMacAddress()
{
    $macParts = [];
    for ($i = 0; $i < 6; $i++) {
        $macParts[] = sprintf('%02x', rand(0, 255));
    }
    return implode(':', $macParts);
}

function curl_get($url, $headers)
{

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_ENCODING, ''); // 自动处理所有支持的编码，包括gzip

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);
    return $response;
}